package com.codedancer.campus.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.codedancer.campus.client.service.ICommentReportService;
import com.codedancer.campus.client.service.bo.commentReport.CommentReportAddBo;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.utils.UUIDGenerator;
import com.codedancer.campus.enums.CommentReportStatus;
import com.codedancer.campus.mapper.CommentReportImageMapper;
import com.codedancer.campus.mapper.CommentReportMapper;
import com.codedancer.campus.mapper.CommentReportTypeMapper;
import com.codedancer.campus.mapper.UserMapper;
import com.codedancer.campus.po.CommentReport;
import com.codedancer.campus.po.CommentReportImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class CommentReportServiceImpl implements ICommentReportService {

  @Autowired
  private CommentReportMapper commentReportMapper;
  @Autowired
  private CommentReportTypeMapper commentReportTypeMapper;
  @Autowired
  private CommentReportImageMapper commentReportImageMapper;
  @Autowired
  private UserMapper userMapper;

  /**
   * 新增举报
   *
   * @param commentReportAddBo
   */
  @Override
  public void add(CommentReportAddBo commentReportAddBo) {
    // 校验数据
    checkCommentReportAddData(commentReportAddBo);
    CommentReport commentReport = BeanUtil.copyProperties(commentReportAddBo, CommentReport.class);
    commentReport.setUuid(UUIDGenerator.getUUID());
    commentReport.setStatus(CommentReportStatus.PENDING_REVIEW);
    commentReport.setReportUserUuid(commentReportAddBo.getCurrentUserUuid());
    commentReportMapper.insert(commentReport);
    // 是否存在举报图片
    if (CollUtil.isNotEmpty(commentReportAddBo.getReportImages())) {
      for (String image : commentReportAddBo.getReportImages()) {
        CommentReportImage commentReportImage = CommentReportImage.builder()
            .uuid(UUIDGenerator.getUUID())
            .commentReportUuid(commentReport.getUuid())
            .imageUrl(image).build();
        commentReportImageMapper.insert(commentReportImage);
      }
    }
  }

  /**
   * 校验评论举报数据
   *
   * @param commentReportAddBo
   */
  private void checkCommentReportAddData(CommentReportAddBo commentReportAddBo) {
    if (!userMapper.existsByUuId(commentReportAddBo.getReportedUserUuid())) {
      throw new BusinessException("被举报用户不存在");
    }
    if (!commentReportTypeMapper.existsByUuId(commentReportAddBo.getCommentReportTypeUuid())) {
      throw new BusinessException("评论举报类型不存在");
    }
    if (commentReportAddBo.getCurrentUserUuid().equals(commentReportAddBo.getReportedUserUuid())) {
      throw new BusinessException("不能举报自己");
    }
  }
}
